package com.panshi.hujin2.httpcrawler.pdf;

import com.panshi.hujin2.httpcrawler.domain.bank.CreditCardBillDo;
import com.panshi.hujin2.httpcrawler.exception.BillAnalysisException;
import com.panshi.hujin2.httpcrawler.util.DateUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * itau银行账单解析
 * @Author: wangxl
 * @Date: 2018/11/23 20:29
 */
public class ItauPdfUtil {

    private static Logger logger = LoggerFactory.getLogger(ItauPdfUtil.class);

    protected static CreditCardBillDo parsePdfFile(String filename) throws IOException {

        logger.info("解析itau银行账单");
        PDDocument document = null;
        try{
            File pdfFile = new File(filename);
            if(!pdfFile.exists()){
                throw new RuntimeException("file does not exist");
            }
            document=PDDocument.load(pdfFile);

            // 获取页码
            int pages = document.getNumberOfPages();

            // 读文本内容
            PDFTextStripper stripper=new PDFTextStripper();
            // 设置按顺序输出
            stripper.setSortByPosition(true);
            stripper.setStartPage(1);
            stripper.setEndPage(pages);
            String content = stripper.getText(document);
            if(content == null || content.length()==0){
                throw new RuntimeException("The contents of the file are empty!");
            }
            String[] lineContent = content.split("\\r\\n");
            if(lineContent == null || lineContent.length==0){
                throw new RuntimeException("The contents of the file are empty!");
            }
            String cpf = null;
            String dueDateStr = null;
            String accountDateStr = null;
            String currency = null;
            String accountAmountStr = null;
            String minRepaymentAmountStr = null;
            String repaymentAmountStr = null;

            Double accountAmount = null;
            Double minRepaymentAmount = null;
            Double repaymentAmount = null;

            String cardId = null;
            for(int i=0;i<lineContent.length;i++){
                String line = lineContent[i];
                //出账日
                if(i==0 && line.endsWith("Banco Itaú Unibanco S.A.")){
                    accountDateStr = line.split(" ")[0];
                }

                if(line.contains("atualização até o seu fechamento.")){
                    String lineA = lineContent[i+1];
                    String[] res = lineA.split(" ");
                    //06/12/2018 648,43
                    dueDateStr = res[0];
                    repaymentAmountStr = res[1];
                }
                //Valor da fatura
                if(line.contains("Valor da fatura")){
                    String lineA = lineContent[i+1].trim();
                    String[] res = lineA.split(" ");
                    // R$ 648,43 31/10 THE BURGER 30,00atual 01/11 CANTINA G 41,94
                    currency = res[0];
                    accountAmountStr = res[1];
                }

                //取卡号
                if(line.trim().startsWith("Cartão:")){
                    String lineA = lineContent[i].trim();
                    String[] res = lineA.split(" ");
                    // Cartão: 5232.XXXX.XXXX.2769
                    cardId = res[1];
                }

            }
            //转换总账单金额
            accountAmountStr = accountAmountStr.replaceAll("\\.","");
            accountAmountStr = accountAmountStr.replace(",",".");
            accountAmount = new Double(accountAmountStr);

            //转换总账单金额
            repaymentAmountStr = repaymentAmountStr.replaceAll("\\.","");
            repaymentAmountStr = repaymentAmountStr.replace(",",".");
            repaymentAmount = new Double(repaymentAmountStr);

            //还款日期
            Date dueDate = null;
            String[] dueDateStrArray = dueDateStr.split("/");
            String dateStr = dueDateStrArray[2]+"-"+dueDateStrArray[1]+"-"+dueDateStrArray[0]+" "+"23:59:59";
            dueDate = DateUtil.parseDateStrToDate(dateStr);

            //出账日期
            Date accountDate = null;
            String[] accountDateStrArray = accountDateStr.split("/");
            dateStr = accountDateStrArray[2]+"-"+accountDateStrArray[1]+"-"+accountDateStrArray[0]+" "+"23:59:59";
            accountDate = DateUtil.parseDateStrToDate(dateStr);
            //账期
            Integer accountPeriod = Integer.valueOf(accountDateStrArray[2]+accountDateStrArray[1]);

            CreditCardBillDo creditCardBillDo = new CreditCardBillDo();
            currency = "REAL";
            creditCardBillDo.setCurrency(currency);
            creditCardBillDo.setAccountDate(accountDate);
            creditCardBillDo.setDueDate(dueDate);
            creditCardBillDo.setMinRepaymentAmount(minRepaymentAmount);
            creditCardBillDo.setRepaymentAmount(repaymentAmount);
            creditCardBillDo.setCardId(cardId);
            creditCardBillDo.setAccountAmount(accountAmount);
            creditCardBillDo.setAccountPeriod(accountPeriod);

            return creditCardBillDo;
        }catch(IOException e){
            logger.info(e.getMessage(),e);
            throw new BillAnalysisException();
        }finally {
            if(document!=null){
                document.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {

        //File f = new File("E:\\需求\\账单\\原件\\Boleto Cartão Celebre.pdf");
        CreditCardBillDo s = parsePdfFile("D:\\1546133858162nujnai@outlook.com.pdf");
    }
}
